package DinnerForScientists;

/**
 * @author welsir
 * @version 1.0
 * @description: TODO
 * @date 2022/10/10 9:54
 */

public class Scientists{

    class test extends Thread{
        private Object[] objects = new Object[]{0,0,0,0,0};
        private int id;

        public test(int id) {
            this.id = id;
        }

        @Override
        public void run() {
            while (true){
                thinking();
                eating();
            }
        }
        public void eating(){
            synchronized (objects[id]){
                if(objects[id].equals(1)){
                    System.out.println("该筷子正在被使用...");
                }else {
                    System.out.println("id:"+id+"拿起了左边的筷子...");
                    objects[id]=0;
                    synchronized (objects[(id+1)%5]){
                        if(objects[(id+1)%5].equals(1)){
                            System.out.println("该筷子正在被使用...");
                        }else {
                            try {
                                System.out.println("id:"+id+"拿起了右边的筷子...");
                                objects[(id+1)%5]=1;
                                Thread.sleep(3000L);
                                System.out.println("id:"+id+"正在吃饭...");
                                System.out.println("id:"+id+"已经吃完了饭...");
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        objects[id]=0;
                        objects[(id+1)%5]=0;
                    }
                }
            }
        }
        public void thinking(){
            try {
                System.out.println("id:"+id+"正在思考...");
                Thread.sleep(3000L);
                System.out.println("id:"+id+"思考完毕，准备吃饭...");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}
